//
//  ReplyViewController.m
//  NewChat
//
//  Created by 马欢 on 16/3/2.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "ReplyViewController.h"
#import "ReplyTableViewCell.h"
#import "PersonalHomePageTableViewController.h"
#import "TopicTableViewController.h"
#import "MHDataHelper.h"
#import "ReplyModel.h"
#import "UserModel.h"
#import "SKXRongCloudManager.h"
#import "SKXFriendManager.h"
#import "PlayerManager.h"

#define HELPER [MHDataHelper shareDataHelper]
#define PLAY [SKXRongCloudManager sharaManager]

@interface ReplyViewController ()<UITableViewDataSource,UITableViewDelegate>
//tableview 回复
@property (weak, nonatomic) IBOutlet UITableView *ReplyTV;
//控件
@property (weak, nonatomic) IBOutlet UIButton *imageBtn;
@property (weak, nonatomic) IBOutlet UILabel *nickL;
@property (weak, nonatomic) IBOutlet UILabel *timeL;
@property (weak, nonatomic) IBOutlet UILabel *replyL;
@property (weak, nonatomic) IBOutlet UILabel *messageL;
@property (weak, nonatomic) IBOutlet UIButton *voiceBtn;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UIButton *replyBtn;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong)UIImageView *backgroundView;

@property (nonatomic,strong)NSMutableArray *replyArray;//回复cell的数组
@property (nonatomic,strong)NSMutableArray *collectArray;//收藏话题的数组

@end

@implementation ReplyViewController
//全局变量 定时器 判断录音时长
static int second = 0;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addviews];
}
//tableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return _replyArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
//设置cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ReplyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReplyListCell"];
    ReplyModel *model =_replyArray[_replyArray.count-1-indexPath.row];
    
    cell.imageBtn.layer.masksToBounds = YES;
    cell.imageBtn.layer.cornerRadius = cell.imageBtn.frame.size.width/2.0;
    cell.voiceBtn.layer.cornerRadius = 20;
    [cell.voiceBtn setTitle:[NSString stringWithFormat:@"                                        %@",model.voiceTime] forState:(UIControlStateNormal)];
    cell.voiceBtn.tag = indexPath.row +201;
    [cell.voiceBtn addTarget:self action:@selector(listenVoice:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.timeL.text = [NSString stringWithFormat:@"%@",model.startTime];
    
    cell.nicknameL.text = model.replyer[@"nickname"];//回复者昵称
    cell.imageBtn.tag = indexPath.row +301;
    [cell.imageBtn addTarget:self action:@selector(toPersonal:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.imageBtn setBackgroundImage:[UIImage imageNamed:model.replyer[@"userImageName"]] forState:(UIControlStateNormal)];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.voiceBtn.layer.borderColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1].CGColor;
    cell.voiceBtn.layer.borderWidth = 1;
    cell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
    cell.voiceBtn.alpha = 0.5;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
//    cell.selectedBackgroundView.backgroundColor = [UIColor purpleColor];
    cell.timeL.textColor = [UIColor grayColor];
    return cell;
}

//看个人信息 两种情况判断 一个push一个pop 根据上层控制器是谁来判断

//看版主 个人信息
-(void)lookHer{

    NSLog(@"让我做个判断");
    
    if ([self.ControlType isEqualToString:@"person"]) {
        HELPER.pushIndex -= 1;
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([self.ControlType isEqualToString:@"topic"]){

        PersonalHomePageTableViewController *personalVC = [[PersonalHomePageTableViewController alloc]init];
        
        personalVC.model = self.findModel;
        personalVC.ControlType = @"push";
//        personalVC.modelType = @"findModel";
        [self.navigationController pushViewController:personalVC animated:YES];
    }
}
//到个人信息 看回复者个人信息
-(void)toPersonal:(UIButton *)sender{
    PersonalHomePageTableViewController *personalVC = [PersonalHomePageTableViewController new];
    //    传值sender.tag
    ReplyModel *reply = self.replyArray[_replyArray.count+300-sender.tag];
    NSLog(@"%ld",_replyArray.count+300-sender.tag);
    personalVC.personalID = reply.replyer.objectId;
    personalVC.modelType = @"replyModel";
    [self.navigationController pushViewController:personalVC animated:YES];
}

//view将出现
-(void)viewWillAppear:(BOOL)animated{
    if ([self.BarType isEqualToString:@"findType"]) {
        //view将要出现 tabbar隐藏
        [self.tabBarController.tabBar setHidden:YES];
    }
//    回复view 请求数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
    [HELPER requestReplyArrayWithOnlyID:self.findModel.objectId didFinish:^(NSMutableArray *array) {
        self.replyArray = array;
        [self.ReplyTV reloadData];
        self.replyL.text = [NSString stringWithFormat:@"%ld回复",self.findModel.replys];
    }];
    });
    
//    判断是否已经收藏
    [self collectOrNot];
}

//=====================发布话题(录音)全在这里===========================
//拉出去 松手 取消录音ok
-(void)cancelReply{
    [[SKXFriendManager sharaFriendManager] cancelRecordVoice];
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"取消录音");
}
//按住 开始录音 添加开启 定时器ok
-(void)startReply:(UIButton *)sender{
    [[PlayerManager defaultManager] pausePlay];
    //    开始录音
    [[SKXFriendManager sharaFriendManager] startRecordVoiceWithFileName:nil];

    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(second) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//定时器 事件
-(void)second{
    second += 1;
    NSLog(@"%d",second);
}
//抬手 结束录音 移掉定时器 判断录音时长 来决定是否存到数据库 并发布（至少4秒）second置零
-(void)endReply{
    [self.timer invalidate];
        self.timer = nil;
    if (second >= 4) {
//  存储 回复语音数据
        ReplyModel *reply = [ReplyModel object];
        reply.replyer = [AVUser currentUser];
        [reply.replyer setObject:[[AVUser currentUser] valueForKey:@"userImageName"] forKey:@"userImageName"];
        // 已知了被分享的该 TodoFolder 的 objectId 语音时长
        reply.voiceTime = [NSString stringWithFormat:@"%d\"",second];
        [reply setObject:[AVObject objectWithoutDataWithClassName:@"FindModel" objectId:self.findModel.objectId] forKey:@"targetFindModel"];
        //停止录音，保存url
        [[SKXFriendManager sharaFriendManager] stopRecordVoiceWithBlock:^(NSString *path) {
            //    存语音
            AVFile *file = [AVFile fileWithName:nil contentsAtPath: path];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {//file保存成功
                    [reply setObject:file.url forKey:@"replyVoice"];
                    [reply saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {//reply保存成功
                            NSLog(@"存储成功");
                        }else{
                            NSLog(@"失败=======%@",error);
                        }
                        [HELPER requestReplyArrayWithOnlyID:self.findModel.objectId didFinish:^(NSMutableArray *array) {
                            self.replyArray = array;
                            [self.ReplyTV reloadData];
                            [HELPER getNumbersOfReplyWithOnlyID:self.findModel.objectId didFinished:^(NSInteger number) {
                                self.replyL.text = [NSString stringWithFormat:@"%ld回复",number];
                            }];
                        }];
                    }];
                }
            }];
        }];//停止录音保存urlblock块，返回一个nsstring *path
}
    second = 0;
}

//==================（一般不改 放在这里）===============================
//懒加载
-(NSMutableArray *)replyArray{
    if (!_replyArray) {
        _replyArray = [NSMutableArray array];
    }
    return _replyArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSMutableArray *)collectArray{
    if (!_collectArray) {
        _collectArray = [NSMutableArray array];
    }
    return _collectArray;
}
//====================（问题很大 必须要改）===========================
//在主题 回复界面判断push几次 返回直接返回第一次主题界面
-(void)backAction{
    if (HELPER.pushIndex >2) {
        TopicTableViewController *topVC = [[self.navigationController viewControllers] objectAtIndex:1];
        [self.navigationController popToViewController:topVC animated:YES];
        HELPER.pushIndex = 0;
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        HELPER.pushIndex -= 1;
    }
}
//收藏话题
-(void)collectHer:(UIButton *)sender{
        RealReachability *reachability = [RealReachability sharedInstance];
        ReachabilityStatus status = [reachability currentReachabilityStatus];
        if (status == RealStatusNotReachable) {
    
        }else{//网络判断
    
    self.collectArray = self.findModel[@"collected"];
    
    if ([self.collectArray containsObject:[AVUser currentUser]]){
        
        //将当前页信息从leanCloud删除
        
        [self.collectArray removeObject:[AVUser currentUser]];
    [self.findModel setObject:self.collectArray forKey:@"collected"];
        [self.findModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
           [sender setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
        }];
        
        
    }else{
        
        //保存当前页面用户信息
        [self.collectArray addObject:[AVUser currentUser]];
        //将保存的信息添加到leanCloud
        [self.findModel setObject:self.collectArray forKey:@"collected"];
        
        [self.findModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [sender setImage:[UIImage imageNamed:@"like1"] forState:(UIControlStateNormal)];
            }
        }];
        
    }
  }//网络判断
}


//判断是否收藏
-(void)collectOrNot{
    //判断网络数组中是否有当前主题帖，如果有就设置为取消收藏
    
    //判断是否包含
    if ([self.findModel[@"collected"] containsObject:[AVUser currentUser]] ) {
        [self.collectBtn setImage:[UIImage imageNamed:@"like1"] forState:(UIControlStateNormal)];
    }else{
        [self.collectBtn setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
    }
}

//================一般不改=================
//听版主话题音频
-(void)HerVoice{
    [[PlayerManager defaultManager] pausePlay];//音乐播放器暂停播放
    [PLAY playRecordSuccessWithURL:self.findModel.messageVoice];
    
}
//听回复音频
-(void)listenVoice:(UIButton *)sender{
    [[PlayerManager defaultManager] pausePlay];//音乐播放器暂停播放
    ReplyModel *reply = self.replyArray[_replyArray.count-sender.tag+200];
    [PLAY playRecordSuccessWithURL:reply.replyVoice];
}
-(void)addviews{
    //加背景图片
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.backgroundView.image = [UIImage imageNamed:@"find3.jpg"];
    [self.view addSubview:self.backgroundView];
    //创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //  毛玻璃view 视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //添加到要有毛玻璃特效的控件中
    effectView.frame = self.backgroundView.bounds;
    //设置模糊透明度（范围0到1）
    effectView.alpha = 0.7f;
    [self.view addSubview:effectView];
    [self.view sendSubviewToBack:effectView];
    [self.view sendSubviewToBack:self.backgroundView];
    // Do any additional setup after loading the view from its nib.
    self.title = @"主题帖";
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    //    注册cell
    UINib *nib = [UINib nibWithNibName:@"ReplyTableViewCell" bundle:nil];
    [self.ReplyTV registerNib:nib forCellReuseIdentifier:@"ReplyListCell"];
    
    [self.imageBtn setBackgroundImage:[UIImage imageNamed:self.findModel.owner[@"userImageName"]] forState:(UIControlStateNormal)];
    self.imageBtn.layer.masksToBounds = YES;
    self.imageBtn.layer.cornerRadius = self.imageBtn.frame.size.width/2.0;
    [self.imageBtn addTarget:self action:@selector(lookHer) forControlEvents:(UIControlEventTouchUpInside)];
    [self.imageBtn setBackgroundImage:[UIImage imageNamed:self.findModel.owner [@"userImageName"]] forState:(UIControlStateNormal)];
    self.nickL.text = self.findModel.owner[@"nickname"];
    self.timeL.text = self.findModel.startTime;
    
    self.replyL.text =  [NSString stringWithFormat:@"%ld回复",self.findModel.replys];
    self.replyL.textAlignment = NSTextAlignmentCenter;
    self.messageL.text = self.findModel.topicMessage;
    self.messageL.numberOfLines = 0;
    self.voiceBtn.layer.cornerRadius = 20;
    NSString *voiceMessage = [NSString stringWithFormat:@"                                   %@\"",self.findModel.messageVoice];
    [self.voiceBtn addTarget:self action:@selector(HerVoice) forControlEvents:(UIControlEventTouchUpInside)];
    self.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
    self.collectBtn.layer.cornerRadius = self.collectBtn.frame.size.width/2.0;
    [self.collectBtn addTarget:self action:@selector(collectHer:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.replyBtn addTarget:self action:@selector(startReply:) forControlEvents:(UIControlEventTouchDown)];
    [self.replyBtn addTarget:self action:@selector(endReply) forControlEvents:(UIControlEventTouchUpInside)];
    [self.replyBtn addTarget:self action:@selector(cancelReply) forControlEvents:(UIControlEventTouchUpOutside)];
    [self.replyBtn  setTitle:@"长按发言 回复:楼主" forState:(UIControlStateNormal)];
    [self.replyBtn setTitle:@"正在录制...回复:楼主" forState:(UIControlStateHighlighted)];
    self.replyBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.replyBtn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    self.replyBtn.layer.masksToBounds = YES;
    self.replyBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"replycolor.jpg"]];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    //    设置代理
    self.ReplyTV.delegate = self;
    self.ReplyTV.dataSource = self;
}
@end
